<template>
  <view class="page-container" :class="themeClass">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      title="统计分析" 
      :show-back="true"
    />
    
    <!-- 页面内容 -->
    <view class="page-content">
      <scroll-view 
        scroll-y 
        class="stats-scroll"
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="refreshData"
      >
        <!-- 时间选择器 -->
        <view class="time-selector">
          <view class="selector-tabs">
            <view 
              class="tab-item" 
              v-for="tab in timeTabs" 
              :key="tab.value"
              :class="{ active: selectedTimeRange === tab.value }"
              @click="selectTimeRange(tab.value)"
            >
              <text class="tab-text">{{ tab.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 总体统计 -->
        <view class="overview-section">
          <view class="section-title">
            <text class="title-text">总体概览</text>
            <text class="title-period">{{ currentPeriodText }}</text>
          </view>
          
          <view class="overview-grid">
            <view class="overview-item">
              <text class="overview-number">{{ statistics.totalDiaries || 0 }}</text>
              <text class="overview-label">总日记数</text>
            </view>
            <view class="overview-item">
              <text class="overview-number">{{ statistics.totalWords || 0 }}</text>
              <text class="overview-label">总字数</text>
            </view>
            <view class="overview-item">
              <text class="overview-number">{{ statistics.writingDays || 0 }}</text>
              <text class="overview-label">写作天数</text>
            </view>
            <view class="overview-item">
              <text class="overview-number">{{ statistics.averageWordsPerDiary || 0 }}</text>
              <text class="overview-label">平均字数</text>
            </view>
          </view>
        </view>
        
        <!-- 分类统计 -->
        <view class="category-stats-section">
          <view class="section-title">
            <text class="title-text">分类统计</text>
          </view>
          
          <view class="stats-list" v-if="statistics.categoryStats && statistics.categoryStats.length > 0">
            <view 
              class="stats-item" 
              v-for="category in statistics.categoryStats" 
              :key="category.categoryId"
            >
              <view class="stats-info">
                <view class="category-icon" :style="{ backgroundColor: category.color + '20' }">
                  <text class="icon-text">{{ category.icon || '📁' }}</text>
                </view>
                <view class="stats-details">
                  <text class="stats-name">{{ category.categoryName }}</text>
                  <text class="stats-meta">{{ category.count }} 篇日记</text>
                </view>
              </view>
              
              <view class="stats-progress">
                <view class="progress-bar">
                  <view 
                    class="progress-fill" 
                    :style="{ 
                      width: category.percentage + '%',
                      backgroundColor: category.color 
                    }"
                  ></view>
                </view>
                <text class="progress-text">{{ category.percentage }}%</text>
              </view>
            </view>
          </view>
          
          <view class="empty-state" v-else>
            <text class="empty-icon">📂</text>
            <text class="empty-title">暂无分类统计</text>
            <text class="empty-desc">开始写日记并设置分类吧</text>
          </view>
        </view>
        
        <!-- 心情统计 -->
        <view class="mood-stats-section">
          <view class="section-title">
            <text class="title-text">心情统计</text>
          </view>
          
          <view class="mood-grid" v-if="statistics.moodStats && statistics.moodStats.length > 0">
            <view 
              class="mood-item" 
              v-for="mood in statistics.moodStats" 
              :key="mood.mood"
            >
              <text class="mood-emoji">{{ getMoodEmoji(mood.mood) }}</text>
              <text class="mood-name">{{ mood.mood }}</text>
              <text class="mood-count">{{ mood.count }} 次</text>
              <text class="mood-percentage">{{ mood.percentage }}%</text>
            </view>
          </view>
          
          <view class="empty-state" v-else>
            <text class="empty-icon">😊</text>
            <text class="empty-title">暂无心情统计</text>
            <text class="empty-desc">记录你的心情变化吧</text>
          </view>
        </view>
        
        <!-- 标签云 -->
        <view class="tag-cloud-section">
          <view class="section-title">
            <text class="title-text">热门标签</text>
          </view>
          
          <view class="tag-cloud" v-if="statistics.tagStats && statistics.tagStats.length > 0">
            <view 
              class="tag-cloud-item" 
              v-for="tag in statistics.tagStats" 
              :key="tag.tagId"
              :style="getTagCloudStyle(tag)"
            >
              <text class="tag-name">{{ tag.tagName }}</text>
              <text class="tag-count">{{ tag.count }}</text>
            </view>
          </view>
          
          <view class="empty-state" v-else>
            <text class="empty-icon">🏷️</text>
            <text class="empty-title">暂无标签统计</text>
            <text class="empty-desc">为你的日记添加标签吧</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <text class="loading-text">⏳</text>
      <text class="loading-desc">加载中...</text>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/user'
import { 
  getWritingStatsAPI, 
  getCategoryStatsAPI, 
  getTagStatsAPI, 
  getMoodStatsAPI,
  getStatsOverviewAPI 
} from '@/api/statistics'
import { formatDate, extractResponseData } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'

export default {
  name: 'StatisticsPage',
  components: {
    CustomNavBar
  },
  setup() {
    const userStore = useUserStore()
    
    return {
      userStore,
      formatDate
    }
  },
  data() {
    return {
      selectedTimeRange: 'month',
      timeTabs: [
        { label: '本周', value: 'week' },
        { label: '本月', value: 'month' },
        { label: '近3月', value: 'quarter' },
        { label: '今年', value: 'year' }
      ],
      statistics: {
        totalDiaries: 0,
        totalWords: 0,
        writingDays: 0,
        averageWordsPerDiary: 0,
        categoryStats: [],
        moodStats: [],
        tagStats: []
      },
      loading: false,
      refreshing: false
    }
  },
  computed: {
    themeClass() {
      return this.userStore.themeMode === 'dark' ? 'theme-dark' : 'theme-light'
    },
    
    currentPeriodText() {
      const now = new Date()
      switch (this.selectedTimeRange) {
        case 'week':
          return '本周'
        case 'month':
          return `${now.getFullYear()}年${now.getMonth() + 1}月`
        case 'quarter':
          return '近3个月'
        case 'year':
          return `${now.getFullYear()}年`
        default:
          return ''
      }
    }
  },
  onLoad() {
    this.initPage()
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 加载统计数据
      await this.loadStatistics()
    },
    
    async loadStatistics() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const res = await getWritingStatsAPI({
          period: this.selectedTimeRange
        })
        
        const data = extractResponseData(res)
        this.statistics = data || {}
        
      } catch (error) {
        console.error('加载统计数据失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async refreshData() {
      this.refreshing = true
      await this.loadStatistics()
      this.refreshing = false
    },
    
    // 选择时间范围
    selectTimeRange(value) {
      if (this.selectedTimeRange === value) return
      
      this.selectedTimeRange = value
      this.loadStatistics()
    },
    
    // 获取心情表情
    getMoodEmoji(mood) {
      const emojiMap = {
        '开心': '😄',
        '快乐': '😊',
        '平静': '😌',
        '悲伤': '😢',
        '愤怒': '😠',
        '焦虑': '😰',
        '兴奋': '🤩',
        '疲惫': '😴',
        '无聊': '😑',
        '感动': '🥺'
      }
      return emojiMap[mood] || '😐'
    },
    
    // 获取标签云样式
    getTagCloudStyle(tag) {
      const minSize = 24
      const maxSize = 40
      const maxCount = Math.max(...this.statistics.tagStats.map(t => t.count))
      const size = minSize + (tag.count / maxCount) * (maxSize - minSize)
      
      return {
        fontSize: `${size}rpx`,
        opacity: 0.6 + (tag.count / maxCount) * 0.4
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}



.page-content {
  padding: 40rpx;
  padding-top: calc(var(--status-bar-height, 44rpx) + 88rpx + 40rpx);
  min-height: calc(100vh - calc(var(--status-bar-height, 44rpx) + 88rpx));
}

.stats-scroll {
  height: 100%;
}

.time-selector {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 8rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.selector-tabs {
  display: flex;
  align-items: center;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16rpx 8rpx;
  border-radius: 16rpx;
  transition: all 0.3s;
}

.tab-item.active {
  background-color: #1890ff;
}

.tab-text {
  font-size: 28rpx;
  color: #666666;
}

.tab-item.active .tab-text {
  color: #ffffff;
  font-weight: bold;
}

.overview-section,
.trend-section,
.category-stats-section,
.mood-stats-section,
.tag-cloud-section {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.title-period {
  font-size: 26rpx;
  color: #666666;
}

.overview-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
}

.overview-item {
  text-align: center;
  padding: 32rpx 16rpx;
  border-radius: 16rpx;
  background-color: #f8f8f8;
}

.overview-number {
  font-size: 48rpx;
  font-weight: bold;
  color: #1890ff;
  display: block;
  margin-bottom: 8rpx;
}

.overview-label {
  font-size: 26rpx;
  color: #666666;
}

.trend-chart {
  height: 400rpx;
  border-radius: 16rpx;
  background-color: #f8f8f8;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
}

.chart-icon {
  font-size: 80rpx;
  margin-bottom: 16rpx;
  display: block;
}

.placeholder-text {
  font-size: 28rpx;
  color: #999999;
}

.stats-list {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.stats-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24rpx;
}

.stats-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
  flex: 1;
}

.category-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-text {
  font-size: 32rpx;
}

.stats-details {
  flex: 1;
}

.stats-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
  display: block;
  margin-bottom: 4rpx;
}

.stats-meta {
  font-size: 24rpx;
  color: #666666;
}

.stats-progress {
  display: flex;
  align-items: center;
  gap: 16rpx;
  width: 200rpx;
}

.progress-bar {
  flex: 1;
  height: 12rpx;
  background-color: #f0f0f0;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 6rpx;
  transition: width 0.3s;
}

.progress-text {
  font-size: 24rpx;
  color: #666666;
  min-width: 60rpx;
  text-align: right;
}

.mood-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 32rpx;
}

.mood-item {
  text-align: center;
  padding: 32rpx 16rpx;
  border-radius: 16rpx;
  background-color: #f8f8f8;
}

.mood-emoji {
  font-size: 64rpx;
  margin-bottom: 12rpx;
  display: block;
}

.mood-name {
  font-size: 26rpx;
  color: #333333;
  font-weight: 500;
  margin-bottom: 8rpx;
  display: block;
}

.mood-count {
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 4rpx;
  display: block;
}

.mood-percentage {
  font-size: 22rpx;
  color: #1890ff;
  font-weight: bold;
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  align-items: center;
  justify-content: center;
  padding: 32rpx 0;
}

.tag-cloud-item {
  background-color: #f0f0f0;
  color: #666666;
  padding: 12rpx 20rpx;
  border-radius: 24rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
  transition: all 0.3s;
}

.tag-cloud-item:active {
  background-color: #e0e0e0;
  transform: scale(0.95);
}

.tag-name {
  font-weight: 500;
}

.tag-count {
  font-size: 20rpx;
  color: #999999;
}

.empty-state {
  text-align: center;
  padding: 80rpx 40rpx;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 24rpx;
  display: block;
}

.empty-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 12rpx;
  display: block;
}

.empty-desc {
  font-size: 26rpx;
  color: #666666;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 1500;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
}

.loading-text {
  font-size: 48rpx;
}

.loading-desc {
  font-size: 28rpx;
  color: #666666;
}

/* 主题适配 */
.theme-light.page-container {
  background-color: #f5f5f5 !important;
}

.theme-dark.page-container {
  background-color: #1e1e1e !important;
}

.theme-dark .time-selector,
.theme-dark .overview-section,
.theme-dark .category-stats-section,
.theme-dark .mood-stats-section,
.theme-dark .tag-cloud-section {
  background-color: #252526 !important;
}

.theme-dark .title-text,
.theme-dark .stats-name,
.theme-dark .mood-name,
.theme-dark .empty-title {
  color: #e8e8e8 !important;
}

.theme-dark .title-period,
.theme-dark .overview-label,
.theme-dark .stats-meta,
.theme-dark .mood-count,
.theme-dark .progress-text,
.theme-dark .empty-desc,
.theme-dark .loading-desc {
  color: #b3b3b3 !important;
}

.theme-dark .overview-number {
  color: #e8e8e8 !important;
}

.theme-dark .tab-item {
  color: #b3b3b3 !important;
}

.theme-dark .tab-item.active {
  background-color: #1890ff !important;
  color: #ffffff !important;
}

.theme-dark .mood-item {
  background-color: #2d2d30 !important;
}

.theme-dark .progress-bar {
  background-color: #404040 !important;
}

.theme-dark .tag-cloud-item {
  background-color: #404040 !important;
  color: #b3b3b3 !important;
}

.theme-dark .tag-count {
  color: #8c8c8c !important;
}

.theme-dark .loading-overlay {
  background-color: rgba(30, 30, 30, 0.8) !important;
}
</style> 